package com.hyt.it.ogt.kq.service.gov.schedule.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * 将统计结果输出成CSV格式文件
 */
@Slf4j
public class ExportStaticCSV {
    
    
    private ExportStaticCSV() {

    }
    
    /**
     * CSV文件生成方法
     * 
     * @param head       文件头
     * @param dataList   数据列表
     * @param outPutPath 文件输出路径
     * @param filename   文件名
     * @return
     */
    public static void createCSVFile(List<String> head, List<List<String>> dataList, String filePath) {
        File csvFile = new File(filePath);
        try (BufferedWriter csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), StandardCharsets.UTF_8), 1024);){
            csvFile.createNewFile();
            // GB2312使正确读取分隔符","GB2312
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<String> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            log.error("## createCSVFile error", e);
        } 
    }

    /**
     * 写一行数据方法
     * 
     * @param row
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuilder sb = new StringBuilder();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }
}
